﻿using Gx.Bll.Manage;
using Gx.Common;
using Gx.Model.Entity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Gx.ColdWarehouseErp.Controllers
{
    public class AttachmentController : Controller
    {
        protected LKAttachmentBll bll = new LKAttachmentBll();
        // GET: Attachment
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns>上传文件结果信息</returns>
        [HttpPost]
        public ActionResult UploadFile()
        {
            HttpPostedFileBase file = Request.Files["file"];
            //接收文本


            if (file != null)
            {
                try
                {
                    string path = Server.MapPath(GlobalHelper.UploadPath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var originalfilename = file.FileName;

                    //获取文件后缀
                    var fileExtension = Path.GetExtension(originalfilename);
                    string filename = string.Empty;
                    //重新命名文件 原文件名+guid
                    if (fileExtension != null)
                    {
                        filename = originalfilename.Replace(fileExtension, "") + Guid.NewGuid() + fileExtension;
                    }
                    var fullname = Path.Combine(path, filename);
                    file.SaveAs(fullname);

                    LKAttachment attachment = new LKAttachment
                    {
                        AttachmentName = filename,
                        OriginalName = originalfilename,
                        CreateTime = DateTime.Now,
                        CreateUserId = LoginHelper.GetUserId(),
                        CreateUser = LoginHelper.UserName()
                    };
                    int i = bll.AddLKAttachment(attachment);

                    return Json(new { id = i });
                }
                catch (Exception ex)
                {
                    return Content(string.Format("上传文件出现异常：{0}", ex.Message));
                }

            }
            else
            {
                return Content("没有文件需要上传！");
            }
        }
    }
}